package cn.bugstack.infrastructure.event;

import cn.bugstack.types.event.BaseEvent;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * @author 19872
 * 消息发送
 */
@Slf4j
@Component
public class EventPublisher {
    private final RabbitTemplate rabbitTemplate;

    public EventPublisher(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    public  void publish(String topic, BaseEvent.EventMessage<?> eventMessage){
        try {
            String messageJson = JSON.toJSONString(eventMessage);
            rabbitTemplate.convertAndSend(topic,messageJson);
        }catch (Exception e){
            log.error("发送MQ消息失败 topic：{} message：{}",topic,JSON.toJSONString(eventMessage),e);
        }
    }

    public void publish(String topic, String messageJson) {
        try {
            rabbitTemplate.convertAndSend(topic, messageJson);
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic：{} message：{}", topic, messageJson, e);
        }
    }
}
